home *** CD-ROM | disk | FTP | other *** search
- Path: cs.tu-berlin.de!news
- From: Roman Lechtchinsky <wolfro@cs.tu-berlin.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Saving a C++ object
- Date: 1 Mar 1996 00:41:27 GMT
- Organization: Technical University of Berlin, Germany
- Message-ID: <4h5h3n$82h@news.cs.tu-berlin.de>
- NNTP-Posting-Host: 130.149.17.223
- Mime-Version: 1.0
- Content-Type: text/plain; charset=iso-8859-1
- Content-Transfer-Encoding: 8bit
-
- Ben Jefferys <brj@doc.ic.ac.uk> writes:
- > When I save a C++ object just using:
- >
- > ----------------------------
- > class ovoid{
- > /* etc. */
- > }
- >
- > ovoid square
- >
- > file.write((unsigned char *) &square, sizeof(ovoid))
- > ----------------------------
- >
- > What *exactly* is saved? I'm finding that every time I recompile
- > an application when I've added some new code, trying to load
- > an object saved in this way with an old version of the application
- > crashes it, even if the class of the object in question hasn't
- > changed. I presume there are some pointers or something which are
- > changing when I add new chunks of code. What can I do to avoid this?
- >
- > (ovoid doesn't containg any explicit pointers which are not reset when
- > reloading - ie. I'm not trying to use old pointers which have
- > been saved - not to my knowledge anyway)
- >
-
- I can only guess, but if you are using virtual functions in ovoid the
- problem can be explained easily. Your compiler ( every compiler, actually )
- stores a pointer to the virtual function table within the object. This
- table contains the addresses of the virtual functions that are to be called
- for this object. When you recompile your program the location of these
- functions in the image is changed. Then, when you read back your object
- the pointer to the table is overwritten and the next time a virtual function
- is called the application crashes. The best solution I've found is
- - assuming you don't want to implement explicit save/load functions -
- to define a struct like
-
- struct _ovoid
- {
- the data you want to save
- };
-
- and then derive ovoid from this struct:
-
- class ovoid : public _ovoid
- {
- the data you don't want to save
-
- member functions
- };
-
- Then you can the object with
- file.write((unsigned char *) (_ovoid *)&square, sizeof(_ovoid)).
-
-
- >
- > Also, is there anything dodgy about saving a class from within itself,
- > using:
- >
- > file.write((unsigned char *) &this, sizeof(ovoid))
- >
-
- No way. Just go on, everybody does it like that.
-
- Bye
-
- Roman
-